﻿using System;
using System.Data;
using System.Web;
using System.Linq;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
using System.IO;
using BluePortal.Medias.Core;

namespace BluePortal.QuikStart.Images
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if(context.Request["vid"]!=null)
            {
                try
                {
                    Guid vid = new Guid(context.Request["vid"]);
                    context.Response.ContentType = "image/jpeg";
                    BCPicture bcp = new BCPicture();
                    bcp.Context.DeferredLoadingEnabled = true;
                    BluePortal.Medias.Core.Picture v = (BluePortal.Medias.Core.Picture)bcp.FindPicureByID(vid);

                    MemoryStream ms =null;
                    if(context.Request["preview"] != null)
                        ms = new MemoryStream(v.Preview);
                    else
                        ms = new MemoryStream(v.Image);
                    Image bm = Bitmap.FromStream(ms);
                    bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    bcp.AddView(v, context.User.Identity.Name);
                }
                catch(Exception ex)
                {
                    Image bmnull = Bitmap.FromFile(context.Server.MapPath("~/Images/miscellaneous.jpg"));
                    bmnull.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
